<?php

namespace App\V3\V3_2\Controllers;

use App\V3\V3_2\Models\SystemConfigModel;
use Illuminate\Http\Request;
use App\V3\V3_2\Models\AdminModel;
use OSS\OssClient;
use App\V3\V3_2\Models\AdminAddendumModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class SystemConfigController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }
    //
    public function set(Request $request)
    {
        if(in_array($request->val, [0, 1])) {
            SystemConfigModel::where('key_value', 'switch')->update(['value' => $request->val]);
            return $this->success();
        }
        else {
            return $this->fail('', '参数不合法');
        }
    }

    public function get()
    {
        $result = SystemConfigModel::where('key_value', 'switch')->first();
        return $this->success(
            $result['value']
        );
    }

    //设置体验版时长
    public function setExperience(Request $request)
    {
        if(!is_numeric($request->value)) {
            return $this->fail('', '输入的内容仅能为数字');
        }

        if(!is_integer($request->value * 1)) {
            return $this->fail('', '输入的内容仅能为整数');
        }
        if($request->value < 0) {
            return $this->fail('', '输入的内容不能小于0');
        }

        SystemConfigModel::where('key_value', 'experience_day')->update(['value' => $request->value]);
        return  $this->success();
    }

    public function getExperience()
    {
        $result = SystemConfigModel::where('key_value', 'experience_day')->first();
        return $this->success(
            $result['value']
        );
    }

    //是否开启系统维护
    public function isUpkeep()
    {
        $info = SystemConfigModel::where('key_value', 'is_upkeep')->first();

        if($info['value']) {
            $info->value = 0;
            $info->save();
            $tag = 0;
        }
        else {
            $info->value = 1;
            $info->save();
            $tag = 1;
        }

        return $this->success($tag);
    }

    //获取开启系统维护信息
    public function getIsUpkeep()
    {
        $info = SystemConfigModel::select('value')->where('key_value', 'is_upkeep')->first();
        return $this->success((int)$info['value']);
    }
    /**
     * 系统微信群图片上传
     * @param Request $request
     */
    public function wxqImgUpload(Request $request){
        $aInfo = AdminModel::select('admin_role')->where(['id'=>$this->getUserId()])->where('delete_flag',0)->first();
        if($aInfo['admin_role'] != 1) return $this->fail('','您不是超级管理员，不能上传系统微信群图片！');
        $sInfo = SystemConfigModel::where(['key_value'=>'wxq_img'])->first();
        if(!empty($file = $request->file('wxq_img'))){
            $img_path = "";
            $res = self::handlePicFormat($file);//判断文件格式
            if(!empty($res)) return $this->fail('',$res['msg']);
            if($file->isValid()){
                $img_path = $file->store('xt/wxq/img/'.date('Y').'-'.date('m').'-'.date('d'));
                $res = SELF::addOssUploadImg($this->getMainUserId(), $this->ossClient, $file, $img_path);
                if($res['code'] == 1) return $this->fail('',$res['msg']);
                $img_path = $res['data'];
            }else{
             return $this->fail('','系统微信群图片，上传失败！');
            }
            DB::getDefaultConnection();
            try {
            if(empty($sInfo)){
                SystemConfigModel::insertGetId(['key_value'=>'wxq_img','value'=>$img_path]);
            }else{
                //删除oss里的文件
                $delOssRes = self::delOssFilePath($sInfo['value'], $this->ossClient, $this->getMainUserId());
                if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                SystemConfigModel::where(['key_value'=>'wxq_img'])->update(['value'=>$img_path]);
            }
            DB::commit();
            return $this->success($img_path);
            } catch (\Exception $e) {
                DB::rollback();
                Log::debug('出库：'.var_export($e->getMessage(), true));
               return $this->fail('','系统微信群图片,上传异常');
            }
        }else{
            return $this->fail('','请选择一个，系统微信群图片！');
        }
    }

    /**
     * 查询系统微信群图片
     * @param Request $request
     */
    public function getWachatGroupImgInfo(Request $request){
        try {

            $sInfo = SystemConfigModel::select('value')->where(['key_value'=>'wxq_img'])->first();

            return $this->success(['path'=>$sInfo['value']]);
            } catch (\Exception $e) {
                return $this->success(['path'=>""]);
            }
    }
    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($mainId,$client,$file,$path){

        $res = handleUploadFileType($file);
        if(!empty($res)) return $res;
        $size = $file -> getSize();
        $result = saveFileSize(['main_id'=>$mainId], $size,$path);
        if($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/'.$path;
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);

            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url').$fullPath;
            return ["code"=>0,"msg"=>"success","data"=>$url];

        } catch (\Exception $e) {

            return ["code"=>1,"msg"=>"OSS系统，上传图片失败！","data"=>""];
        }
    }

    /**
     * 处理图片和视频格式
     */
    static public function handlePicFormat($files){

        $pic_format  = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';
        $ext = $files->extension();

        $ext = strtolower($ext);

      $pic_video_format_arr = explode(',',$pic_format);

        if (!in_array($ext, $pic_video_format_arr)) {

            return ['code' => 1,'msg' => '图片格式，不正确','data' => ''];
        }

    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){

        if(empty($file)) return $file;

        DB::beginTransaction();
        try {
            $delPath = strstr($file, 'uploads/');
            $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
            AdminAddendumModel::where(['main_id'=>$mainId])
            ->decrement('file_total_size', $imgInfo['content-length']);
            $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

        }

    }
}
